<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\News;
use app\models\Page;


class AdminController extends Controller
{
	// public $enableCsrfValidation = false;//取消跨域的验证

	function actionNews(){
		if(Yii::$app->user->isGuest){
			// throw new \yii\web\HttpException(404);
		}
		$model =new News();
		$catname = Yii::$app->params['cat_name'];
		$p= Yii::$app->request->post();
		$g= Yii::$app->request->get();
		$id=$g['id'];//request请求
		switch($g['do']){  // Yii::$app->request->get('action') =>$_GET['action']
			case 'create':
				if($_POST){
					if($id = $model -> createNews()){
						// $this->redirect(['article/content','slug'=>$p['cid'],'id'=>$id]);
						$this->redirect(['article/content','catid'=>$catname[$dataArray['catid']]['slug'],'slug'=>$dataArray['slug']]);
						//redirect跳转至CONTENT方法，直接显示
					}else{
						echo "<script>alert('修改失败');history.go(-1)</script>";//弹出‘修改失败’对话框，点击确定，返回上一页。
					}
				}else{
					return $this->render('newsCreate');
				}
				break;//跳出'CREATE'SWITCH循环
			case 'dele':
				if($model -> deleNews($id)){
					echo "<script>self.location=document.referrer;</script>";
					//设置当前链接为上一页的链接，这一页即删除了
				}else{
					echo "删除失败！";
				}
				break;
			case 'edit':
				$data = News::findOne($id);//外部引用findOne()方法
				$dataArray = $data->attributes;
				if($_POST){
					if($model -> editNews($data)){
						$this->redirect(['article/content','catid'=>$catname[$dataArray['catid']]['slug'],'slug'=>$dataArray['slug']]);
					}else{
						// $this->goBack();
						echo "<script>alert('修改失败');history.go(-1)</script>";//弹出‘修改失败’对话框，点击确定，返回上一页。
					}
				}else{
					return $this->render('newsEdit',['data'=>$dataArray]);
					//渲染一个视图
				}
				break;
			default://默认
				// $count = $model -> getNewsListCount();
				// $pagination = new Pagination(['totalCount' => $count]);
				// $pagination->defaultPageSize =5;//设置默认页面内容条数
				// $data = $model -> getNewsList($pagination);
				// return $this -> render('index',['data'=>$data,'page'=>$pagination]);
				// break;

				$count = $model -> getNewsListCount(-2);
				$perCount = 10;
				$data = $model -> getNewsList($perCount,-2);
				$html = Page::getPageHtml($count,'admin/news',$perCount,2,3);
				return $this -> render('index',['data'=>$data,'pageHtml'=>$html]);
		}
	}
}